package com.gdufe.firesafe.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gdufe.firesafe.dao.MessageDao;
import com.gdufe.firesafe.exception.RRException;
import com.gdufe.firesafe.model.constants.MessageFilterType;
import com.gdufe.firesafe.model.constants.RoleConstant;
import com.gdufe.firesafe.model.constants.UrgentLevelConstant;
import com.gdufe.firesafe.model.entity.InspectionEntity;
import com.gdufe.firesafe.model.entity.MessageEntity;
import com.gdufe.firesafe.model.entity.UserEntity;
import com.gdufe.firesafe.service.HouseService;
import com.gdufe.firesafe.service.MessageService;
import com.gdufe.firesafe.service.UserService;
import com.gdufe.firesafe.utils.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static com.gdufe.firesafe.model.enums.InspectionItemEnum.*;

@Service("messageService")
public class MessageServiceImpl extends ServiceImpl<MessageDao, MessageEntity> implements MessageService {
    @Resource
    private HouseService houseService;
    @Resource
    private UserService userService;

    @Override
    public MessageEntity saveByInspection(InspectionEntity inspection) {
        //紧急程度分为1，2，3级，多个隐患选择最高级的显示
        int urgentLevel = 0;//最终为0则不需要发提醒消息
        StringBuilder messageContent = new StringBuilder();
        //疏通通道0分-3级，1分-2级，2分-1级，3分-0级
        Integer passageUnblockStatus = inspection.getPassageUnblockStatus();
        switch (passageUnblockStatus) {
            case 0:
                urgentLevel = Math.max(urgentLevel, UrgentLevelConstant.HIGH);
                messageContent.append("逃生通道严重堵塞\n");
                break;
            case 1:
                urgentLevel = Math.max(urgentLevel, UrgentLevelConstant.MIDDLE);
                messageContent.append("逃生通道中等堵塞\n");
                break;
            case 2:
                urgentLevel = Math.max(urgentLevel, UrgentLevelConstant.LOW);
                messageContent.append("逃生通道轻度堵塞\n");
                break;
            case 3:
                break;
            default:
        }
        //detectorNoError0分-3级，detectorSelfTest0分-2级，detectorElectricity0分-1级
        if (!inspection.getDetectorNoError()) {
            urgentLevel = Math.max(urgentLevel, DETECTOR_NO_ERROR.getUrgentLevel());
            messageContent.append(DETECTOR_NO_ERROR.getWarnMessage());
        }
        if (!inspection.getDetectorSelfTest()) {
            urgentLevel = Math.max(urgentLevel, DETECTOR_SELF_TEST.getUrgentLevel());
            messageContent.append(DETECTOR_SELF_TEST.getWarnMessage());
        }
        if (!inspection.getDetectorElectricity()) {
            urgentLevel = Math.max(urgentLevel, DETECTOR_ELECTRICITY.getUrgentLevel());
            messageContent.append(DETECTOR_ELECTRICITY.getWarnMessage());
        }
        //gasNoLeakage和gasAutomaticShutOff有一个0分就3级，gasMeterStatus0分-2级
        if (!inspection.getGasNoLeakage()) {
            urgentLevel = Math.max(urgentLevel, GAS_NO_LEAKAGE.getUrgentLevel());
            messageContent.append(GAS_NO_LEAKAGE.getWarnMessage());
        }
        if (!inspection.getGasAutomaticShutOff()) {
            urgentLevel = Math.max(urgentLevel, GAS_AUTOMATIC_SHUT_OFF.getUrgentLevel());
            messageContent.append(GAS_AUTOMATIC_SHUT_OFF.getWarnMessage());
        }
        if (!inspection.getGasMeterStatus()) {
            urgentLevel = Math.max(urgentLevel, GAS_METER_STATUS.getUrgentLevel());
            messageContent.append(GAS_METER_STATUS.getWarnMessage());
        }
        //circuitStatus3级，electricalInsulation，standbyPower，electricalGrounding2级，electricalLoad1级
        if (!inspection.getCircuitStatus()) {
            urgentLevel = Math.max(urgentLevel, CIRCUIT_STATUS.getUrgentLevel());
            messageContent.append(CIRCUIT_STATUS.getWarnMessage());
        }
        if (!inspection.getElectricalInsulation()) {
            urgentLevel = Math.max(urgentLevel, ELECTRICAL_INSULATION.getUrgentLevel());
            messageContent.append(ELECTRICAL_INSULATION.getWarnMessage());
        }
        if (!inspection.getStandbyPower()) {
            urgentLevel = Math.max(urgentLevel, STANDBY_POWER.getUrgentLevel());
            messageContent.append(STANDBY_POWER.getWarnMessage());
        }
        if (!inspection.getElectricalGrounding()) {
            urgentLevel = Math.max(urgentLevel, ELECTRICAL_GROUNDING.getUrgentLevel());
            messageContent.append(ELECTRICAL_GROUNDING.getWarnMessage());
        }
        if (!inspection.getElectricalLoad()) {
            urgentLevel = Math.max(urgentLevel, ELECTRICAL_LOAD.getUrgentLevel());
            messageContent.append(ELECTRICAL_LOAD.getWarnMessage());
        }
        //灭火器3级
        if (!inspection.getExtinguisherLeadSealing()) {
            urgentLevel = Math.max(urgentLevel, EXTINGUISHER_LEAD_SEALING.getUrgentLevel());
            messageContent.append(EXTINGUISHER_LEAD_SEALING.getWarnMessage());
        }
        if (!inspection.getExtinguisherPressure()) {
            urgentLevel = Math.max(urgentLevel, EXTINGUISHER_PRESSURE.getUrgentLevel());
            messageContent.append(EXTINGUISHER_PRESSURE.getWarnMessage());
        }
        if (!inspection.getExtinguisherDamaged()) {
            urgentLevel = Math.max(urgentLevel, EXTINGUISHER_DAMAGED.getUrgentLevel());
            messageContent.append(EXTINGUISHER_DAMAGED.getWarnMessage());
        }
        if (!inspection.getExtinguisherExpired()) {
            urgentLevel = Math.max(urgentLevel, EXTINGUISHER_EXPIRED.getUrgentLevel());
            messageContent.append(EXTINGUISHER_EXPIRED.getWarnMessage());
        }
        if (messageContent.length() == 0) {
            messageContent.append("暂无安全隐患");
        }

        String title = "你有新的房屋检查记录";
        if (urgentLevel != UrgentLevelConstant.NONE) {
            title += "，有安全隐患警告！";
        }
        Integer ownerId = houseService.getById(inspection.getHouseId()).getOwnerId();
        Integer userId = userService.lambdaQuery().eq(UserEntity::getRoleId, ownerId).one().getId();
        //数据库存入消息
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setReceiverId(userId);
        messageEntity.setInspectionId(inspection.getId());
        messageEntity.setTitle(title);
        messageEntity.setContent(messageContent.toString());
        messageEntity.setCreatedTime(new Date());
        messageEntity.setLevel(urgentLevel);
        messageEntity.setTargetRole(RoleConstant.OWNER);
        this.save(messageEntity);

        return messageEntity;
    }

    @Override
    public Integer getUnreadCount() {
        Integer userId = TokenUtils.getCurrentUser().getId();
        return this.lambdaQuery().eq(MessageEntity::getHasRead, false).eq(MessageEntity::getReceiverId, userId).count();
    }

    @Override
    public List<MessageEntity> list(Integer type) {
        Integer userId = TokenUtils.getCurrentUser().getId();
        switch (type) {
            case MessageFilterType.ALL:
                return this.lambdaQuery().eq(MessageEntity::getReceiverId, userId).list();
            case MessageFilterType.UNREAD:
                return this.lambdaQuery().eq(MessageEntity::getHasRead, false).eq(MessageEntity::getReceiverId, userId).list();
            case MessageFilterType.READ:
                return this.lambdaQuery().eq(MessageEntity::getHasRead, true).eq(MessageEntity::getReceiverId, userId).list();
            default:
                throw new RRException("无效的筛选类型");
        }
    }

    @Override
    public boolean readAll() {
        Integer userId = TokenUtils.getCurrentUser().getId();
        return this.lambdaUpdate().eq(MessageEntity::getReceiverId, userId).set(MessageEntity::getHasRead, true).update();
    }

    @Override
    public boolean read(Integer messageId) {
        return this.lambdaUpdate().eq(MessageEntity::getId, messageId).set(MessageEntity::getHasRead, true).update();
    }
}
